<?php

/**
 * TODO: eliminar el require_once
 */
require_once 'Place.class.php';
require_once 'Forecast.class.php';

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Beach
 *
 * @author Albert
 */
class Beach extends Place {
    
  public $idLocation;
	public $forecast;
	public $webcams;
    
    public function __construct() {
			parent::__construct();
			$this->idLocation = null;
			$this->forecast = new Forecast;
    }
    
    
    /* Setters ********************************* */
    public function setIdLocation($id) {
        $this->idLocation = $id;
    }
    
    
    /* Getters ******************************** */
    public function getIdLocation() {
        return $this->idLocation;
    }
	
    public function getLocationString() {
		$result = db_query("select name from location where id = %d",$this->idLocation);
        return db_fetch_object($result)->name;
    }
	
	public function getForecast($date){
		$result = db_query("select count(*) as count from forecast where idBeach = {$this->id} and date = '{$date}'");
		$data = db_fetch_object($result);
		
		if($data->count == 0){
			openplaya_importar($this->id);
		}
		$sql = "select * from forecast where idBeach = {$this->id} and date = '{$date}'";
		$result = db_query($sql);
		$data = db_fetch_object($result);
		$this->forecast->setId($data->id);
		$this->forecast->setIdBeach($data->idBeach);
		$this->forecast->setDate($data->date);
		$this->forecast->setStatusSkyAm($data->statusSkyAm);
		$this->forecast->setStatusSkyPm($data->statusSkyPm);
		$this->forecast->setStatusWindAm($data->statusWindAm);
		$this->forecast->setStatusWindPm($data->statusWindPm);
		$this->forecast->setStatusSwellAm($data->statusSwellAm);
		$this->forecast->setStatusSwellPm($data->statusSwellPm);
		$this->forecast->setHighTideAm($data->highTideAm);
		$this->forecast->setHighTidePm($data->highTidePm);
		$this->forecast->setLowTideAm($data->lowTideAm);
		$this->forecast->setLowTidePm($data->lowTidePm);
		$this->forecast->setTMax($data->tMax);
		$this->forecast->setTWater($data->tWater);
		$this->forecast->setThermalSensation($data->thermalSensation);
		$this->forecast->setUvIndex($data->uvIndex);
		$this->forecast->setWarningJellyfish($data->warningJellyfish);
		$this->forecast->setWarningShark($data->warningShark);
		$this->forecast->setFlag($data->flag);
	}
	
	public function render($mode,$tomorrow = false){
		if($tomorrow) $date = date('Y-m-d',strtotime("+1 day"));
		else $date = date('Y-m-d');
		
		switch($mode){
			case 'full':
				$this->getForecast($date);			
				
				if($tomorrow) $link_tomorrow = l('Ver previsión hoy','playas/'.$this->id.'/');
				else  $link_tomorrow = l('Ver previsión mañana','playas/'.$this->id.'/manana/');
				
				$fields = array(
					//array('name','Nombre de la playa',$this->getName()),
					array('rating',t('Rating'), $this->getRating()),
					array('location',t('Location'),geocodeGoogleLocation($this->getLatiude(),$this->getLongitude()).' (<a class="gmapslink" href="http://maps.google.es/maps?q='. $this->getLatiude() .','. $this->getLongitude() .'">Ver en google maps</a>)'),
					array('date',t('Forecast date'),date('d-m-Y',strtotime($date)) .' - '. $link_tomorrow),
					array('tmax',t('Maximum temperature'),$this->forecast->getTMax()."ºC"),
					array('thermalSensation',t('Feels like'),sensation2code($this->forecast->getThermalSensation(),true)),
					array('tagua',t('Water temperature'),$this->forecast->getTWater()."ºC"),
					array('indexUV',t('!uv index',array('!uv'=>'<acronym title="' . t('Ultraviolete') . '">'. t('UV') . '</acronym>')),$this->forecast->getUvIndex())
				);
				$skystatus = array(
					array('skyam',$this->forecast->getStatusSkyAm(),sky2code($this->forecast->getStatusSkyAm(),true)),
					array('skypm',$this->forecast->getStatusSkyPm(),sky2code($this->forecast->getStatusSkyPm(),true)),
				);
				
				$windstatus = array(
					array('windam',$this->forecast->getStatusWindAm(),wind2code($this->forecast->getStatusWindAm(),true)),
					array('windpm',$this->forecast->getStatusWindPm(),wind2code($this->forecast->getStatusWindPm(),true)),
				);
				
				$swellstatus = array(
					array('swellam',$this->forecast->getStatusSwellAm(),wind2code($this->forecast->getStatusSwellAm(),true)),
					array('swellpm',$this->forecast->getStatusSwellPm(),wind2code($this->forecast->getStatusSwellPm(),true)),
				);
				$html = array();
				foreach($fields as $field)
					$html[] = '<div class="field '.$field[0].'"><span class="label">'.$field[1].':</span><span class="value">'.$field[2].'</span></div>';
					
				$html[] ='<br/><div class="forecast-resume"><div class="am"><span>Mañana</span></div><div class="pm"><span>Tarde</span></div>';
					
				foreach($skystatus as $sky)
					$html[] = '<div class="sky '.$sky[0].'"><img class="skystatus" src="/images/skystatus'.$sky[1].'.png" title="'.$sky[2].'" alt="'.$sky[2].'"/></div>';
				foreach($windstatus as $wind)
					$html[] = '<div class="wind '.$wind[0].'"><span class="value">'.t('Wind').' '.$wind[2].'</span></div>';
				foreach($swellstatus as $swell)
					$html[] = '<div class="swell '.$swell[0].'"><span class="value">'.t('Swell').' '.$swell[2].'</span></div>';
					$html[] = '<br/><br/>';
				$html[] ='</div>';
				$webcams = $this->getUrlWebcams();
				if(!empty($webcams)){
				$html[] = '<div class="webcam">';
					$html[] = '<p><strong>Webcam</strong></p>';
					foreach($webcams as $webcam){
						$html[] = '<img alt="webcam" src="'.$webcam.'?'.str_random().'" />';
					}
				$html[] = '</div><br/>';
				}
				$highTideAm = date('H:i',strtotime($this->forecast->getHighTideAm()));
				$highTidePm = date('H:i',strtotime($this->forecast->getHighTidePm()));
				$lowTideAm = date('H:i',strtotime($this->forecast->getLowTideAm()));
				$lowTidePm = date('H:i',strtotime($this->forecast->getLowTidePm()));
				if((!empty($highTideAm) && ($highTideAm != '00:00')) ||
					(!empty($highTidePm) && ($highTidePm != '00:00')) ||
					(!empty($lowTideAm) && ($lowTideAm != '00:00')) ||
					(!empty($lowTidePm) && ($lowTidePm != '00:00'))){
					
					$form_tide = array();
					$form_tide['infotide'] = array(
						'#title' => t('Tide information'),
						'#type' => 'fieldset',
						'#attributes' => array('class' => 'infotide'),
						'#collapsible' => TRUE,
						'#collapsed' => TRUE,
					);
					$form_tide['infotide']['caption'] = array(
						'#value' => '<div class="info_tide"><table><tr><th></th><th><strong>'.t('Morning').'</strong></th><th><strong>'.t('Evening').'</strong></th></tr>',
						'#weight' => 1
					);
					 $form_tide['infotide']['hightide'] = array(
						'#value' => '<tr><td>'.t('High tide').'</td><td>'. $highTideAm .'</td><td>'. $highTidePm .'</td></tr>',
						'#weight' => 2
					);
					$form_tide['infotide']['lowtide'] = array(
						'#value' => '<tr><td>'.t('Low tide').'</td><td>'. $lowTideAm .'</td><td>'. $lowTidePm .'</td></tr></table></div>',
						'#weight' => 3
					);
					$html[] = drupal_render_form('InformacionMareas',$form_tide);
				}
				$html[] = '<div class="equipment_list">';
				$html[] = '<br/><p><strong>'.t('List of nearby equipments').'</strong></p>';
				$equipments = $this->getEquipments();
				$code_equipments = array();
				foreach($equipments as $equipment){
					if(empty($code_equipments[$equipment->idType])){
						$data = db_fetch_object(db_query('select name from equipationtype where id='.$equipment->idType));
						$code_equipments[$equipment->idType] = $data->name;
					}
					$rows[] = array('<img src="/images/markers/marker'.$equipment->idType.'.png" alt="'.$code_equipments[$equipment->idType].'" />',$equipment->name,$code_equipments[$equipment->idType]);
				}
				if(!empty($rows))
					$html[] = theme_table(array('',t('Name'),t('Type')),$rows,array('class' => 'equipment_table'));
				//var_dump($equipments);
				$html[] = '</div>';
				$link = l(t('Register and recive notifications'),'user/register',array('query'=>array('source'=>$this->getName())));
				$html[] = '<div class="subscribe">' . t('Do you like this beach?') . ' '. t('!register_and_be_notified about forecasts for this beach!', array('!register_and_be_notified'=>$link)) .'</div>';
				return implode('',$html);
			break;
			case 'marker':
					$fields = array(
						array('name',t('Name'),$this->getName()),
						array('location',t('Location'),$this->getLocationString()),
					);
					$html = array();
					foreach($fields as $field)
						$html[] = '<div class="field '.$field[0].'"><span class="label">'.$field[1].':</span> <span class="value">'.$field[2].'</span></div>';
					$html[] = l(t('More info'),'playas/'.$this->getId());
					return implode('',$html);
			break;
		}
	}
    /**
     * Devuelve un array de objetos Equipment
     * 
     * @return Equipment Devuelve un array de objetos Equipment
     */
    public function getEquipments() {
        
        $equip = array();
        
        $sql = "
            SELECT *
            FROM equipation
            WHERE idBeach = {$this->id} ";
       
      $result = db_query($sql);
      
      $i = 0;
      
      while($e = db_fetch_array($result)) {
          $equip[$i] = new Equipment();
          $equip[$i]->setId($e['id']);
          $equip[$i]->setIdType($e['idType']);
          $equip[$i]->setLatitude($e['latitude']);
          $equip[$i]->setLongitude($e['longitude']);
          $equip[$i]->setName($e['name']);
          $equip[$i]->setUrl($e['url']);
          $i++;
      }
      return $equip;
    }
	
	/**
     * Devuelve un array de objetos Webcam
     * 
     * @return Webcam Devuelve un array de objetos Webcam
     */
	 
	 public function getUrlWebcams() {
		$webcams = array();
		$sql = "
            SELECT *
            FROM webcam
            WHERE idBeach = {$this->id}";
       
		$result = db_query($sql);
		while($webcam = db_fetch_array($result)) {
			$webcams[] = $webcam['url'];
		}
        return $webcams;
    }

    
    
    public function setRating($puntuacion){
        $rating = (int)$puntuacion;
        $id = (int)$this->getId();
		
        $result = db_query("SELECT * FROM beach WHERE id = ".$id);
		$data = db_fetch_object($result);
		
		if($rating > 5 || $rating < 1) {
		  $output = "<div class='highlight'>No se puede puntuar por debajo de 1 o mayor de 5</div>";
		}
		elseif(isset($_COOKIE['rated'.$id])) {
			$output = "<div class='highlight'>¡Ya has votado!</div>";
		}
		else {
			setcookie("rated".$id, $id, time()+60*60*24*365);
			$total_rating = $data->totalRating;
			$total_ratings = $data->totalRatings;
			//$current_rating = $data->rating;

			$new_total_rating = $total_rating + $rating;
			$new_total_ratings = $total_ratings + 1;
			$new_rating = $new_total_rating / $new_total_ratings;
			
			// Actualizamos los datos.
			db_query("UPDATE beach SET totalRating = '".$new_total_rating."' WHERE id = '".$id."'");
			db_query("UPDATE beach SET rating = '".$new_rating."' WHERE id = '".$id."'");
			db_query("UPDATE beach SET totalRatings = '".$new_total_ratings."' WHERE id = '".$id."'");
			$output = "<div class='highlight'>¡Se ha guardado tu voto!</div>";
		}
		return $output;
    }
    
    
    public function getRating() {
        $result = db_query("select id, rating, totalRating, totalRatings from beach where id={$this->getId()}");
        $data = db_fetch_object($result);
        
		$rating = (int)$data->rating;
        
        $rat1 = "_blank";
        $rat2 = "_blank";
        $rat3 = "_blank";
        $rat4 = "_blank";
        $rat5 = "_blank";
        
         if($rating > 0) { $rat1 = ""; }
         if($rating > 1) { $rat2 = "";}
         if($rating > 2) { $rat3 = "";}
         if($rating > 3) { $rat4 = "";}
         if($rating > 4) { $rat1 = "";}
        
        $html = '<div id="estrellas" class="floatleft">';
        $html .= '<div id="rating_'.$data->id.'">';
                            $html .= '<span class="star_1"><img src="/images/star'.$rat1.'.png" alt="star_1" /></span>';
                            $html .= '<span class="star_2"><img src="/images/star'.$rat2.'.png" alt="star_2" /></span>';
                            $html .= '<span class="star_3"><img src="/images/star'.$rat3.'.png" alt="star_3" /></span>';
                            $html .= '<span class="star_4"><img src="/images/star'.$rat4.'.png" alt="star_4" /></span>';
                            $html .= '<span class="star_5"><img src="/images/star'.$rat5.'.png" alt="star_5" /></span>';
                    $html .= '</div>';
            $html .= '</div>';
            $html .= '<div class="star_rating">';
					if(empty($data->totalRatings)) $totalRatings = 0;
					else $totalRatings = $data->totalRatings;
                    $html .= '(Votado <strong>'.$totalRatings.'</strong> veces)';
            $html .= '</div>';

            $html .= '<div class="clearleft">&nbsp;</div>';
      
		return $html;
    }
}

?>
